package com.zbystudy.factory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import static org.apache.commons.lang3.StringUtils.isEmpty;

/**
 * Created By zby on 15:23 2019/3/31
 */

public class sqlConnectFactory {

    private sqlConnectFactory() {

    }


    /**
     * 创建property的配置文件
     */
    private static Properties properties;


    //【2】静态代码块
    static {
        //加载配置文件
        properties = new Properties();
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            System.out.println("未找到配置文件");
            e.printStackTrace();
        }
    }

    /**
     * Created By zby on 16:50 2019/1/23
     * 获取数据连接
     */
    public static Connection createConnect() {
        String driverName = properties.getProperty("jdbc.driver");
        if (isEmpty(driverName)) {
            driverName = "com.mysql.jdbc.Driver";
        }
        String userName = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        String dbUrl = properties.getProperty("jdbc.url");

        try {
            Class.forName(driverName);
            return DriverManager.getConnection(dbUrl, userName, password);
        } catch (ClassNotFoundException e) {
            System.out.println("找不到驱动类");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("加载异常");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Created By zby on 22:15 2019/4/1
     * 获取配置文件的信息
     */
    public static Properties getProperties() {
        return properties;
    }
}
